package com.wk.fallback;

import com.wk.dto.ResponseResult;
import com.wk.util.JsonUtil;
import org.springframework.cloud.netflix.zuul.filters.route.FallbackProvider;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.stereotype.Component;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * 网关容错，服务宕机后提供自定义的错误信息
 */
@Component
public class ZuulFallBack implements FallbackProvider {

	@Override
	public String getRoute() {
		return "*";		//*对所有服务生效
	}

	@Override
	public ClientHttpResponse fallbackResponse(String route, Throwable cause) {
		return new ClientHttpResponse() {
			@Override
			public HttpStatus getStatusCode() throws IOException {
				return HttpStatus.BAD_REQUEST;
			}

			@Override
			public int getRawStatusCode() throws IOException {
				return HttpStatus.BAD_REQUEST.value();
			}

			@Override
			public String getStatusText() throws IOException {
				return "提示信息";
			}

			@Override
			public void close() {

			}

			@Override
			public InputStream getBody() throws IOException {
				//通用返回值转成字符串，再转成byte数组返回，方便前端处理
				return new ByteArrayInputStream(JsonUtil.obj2String(ResponseResult.fail(-1, "fail")).getBytes());
			}

			@Override
			public HttpHeaders getHeaders() {
				HttpHeaders headers = new HttpHeaders();
				headers.setContentType(MediaType.APPLICATION_JSON);
				return headers;
			}
		};
	}
}
